# coding: utf-8
from rest_framework.response import Response
from rest_framework import status
from rest_framework.validators import ValidationError
from functools import wraps

"""
异常模块
=======

"""
__author__ = 'lee'


def catch_exception(func):
    """
    抓取异常的装饰器，统一抓取抛出的异常，处理记录日志并返回结果。
    :param func:
    :return Response:
    """

    @wraps(func)
    def deco(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except ValidationError as e:
            errors = e.detail
            return Response({
                "msg": '\n'.join(
                    ["{0}:{1}".format(k, ','.join(v)) for k, v in errors.items()])},
                status.HTTP_400_BAD_REQUEST)
    return deco
